package com.example.controller;

import com.example.pojo.DepartItem_Pojo;
import com.example.pojo.Reg_Pojo;
import com.example.service.DepartItemService;
import com.example.service.RegService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Controller
@RequestMapping("/reg")
public class RegController {

    @Autowired
    private RegService regService;
    
    @Autowired
    private DepartItemService departItemService;

    @GetMapping("/list")
    public String list(Model model) {
        List<Reg_Pojo> regs = regService.listAll();
        // Build a map from DepartID -> DepartName for rendering
        List<DepartItem_Pojo> departItems = departItemService.getDepartItem();
        Map<Integer, String> departNameMap = new HashMap<>();
        for (DepartItem_Pojo d : departItems) {
            try {
                if (d.getDepartID() != null) {
                    departNameMap.put(Integer.parseInt(d.getDepartID()), d.getDepartName());
                }
            } catch (NumberFormatException ignored) { }
        }
        model.addAttribute("regs", regs);
        model.addAttribute("departNameMap", departNameMap);
        return "Reg/list";
    }

    @GetMapping("/addForm")
    public String addForm(Model model) {
        model.addAttribute("reg", new Reg_Pojo());
        List<DepartItem_Pojo> departItems = departItemService.getDepartItem();
        model.addAttribute("departItems", departItems);
        return "Reg/addForm";
    }

    @PostMapping("/add")
    public String add(@ModelAttribute Reg_Pojo reg) {
        regService.insert(reg);
        return "redirect:/reg/list";
    }

    @GetMapping("/editForm")
    public String editForm(@RequestParam Integer id, Model model) {
        Reg_Pojo reg = regService.getById(id);
        model.addAttribute("reg", reg);
        List<DepartItem_Pojo> departItems = departItemService.getDepartItem();
        model.addAttribute("departItems", departItems);
        return "Reg/editForm";
    }

    @GetMapping("/editForm/{id}")
    public String editFormPath(@PathVariable Integer id, Model model) {
        return editForm(id, model);
    }

    @PostMapping("/update")
    public String update(@ModelAttribute Reg_Pojo reg) {
        regService.update(reg);
        return "redirect:/reg/list";
    }

    @PostMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        regService.delete(id);
        return "redirect:/reg/list";
    }
}
